package com.cncf.controller.user;

import com.cncf.entity.Enterprise;
import com.cncf.entity.EnterpriseVo;
import com.cncf.response.ResponseData;
import com.cncf.service.EnterpriseService;
import com.cncf.util.JedisUtil;
import com.cncf.util.ObjectAndByte;
import com.cncf.util.TokenConfig;
import com.cncf.util.Util;
import com.cncf.vo.LoginVo;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author zj
 */
@Api(value = "User", description = "用户端企业的相关接口")
@Controller
@RequestMapping("/user/enterprise")
public class UserEnterpriseController {
    private static final Logger logger = LoggerFactory.getLogger(UserEnterpriseController.class);

    @Autowired
    private EnterpriseService enterpriseService;

    @ApiOperation(value = "用户通过企业公用密码登录", notes = "")
    @RequestMapping(value = "userLogin", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData<LoginVo> userLogin(
            @ApiParam("企业名") @RequestParam("enterpriseName") String enterpriseName,
            @ApiParam("密码") @RequestParam("password") String password,
            HttpServletRequest request, HttpServletResponse response) {

        ResponseData<LoginVo> responseData = new ResponseData();
        Enterprise enterprise = enterpriseService.getEnterpriseByName(enterpriseName).get(0);
        if (enterprise == null) {
            responseData.jsonFill(2, "用户不存在", null);
            return responseData;
        }
        if (!enterprise.getPassword().equals(password)) {
            responseData.jsonFill(2, "用户名或密码错误。", null);
            return responseData;
        }
        enterprise.setAccesstoken(Util.getToken());

        //登录信息写入缓存
        Jedis jedis = null;
        try {
            jedis = JedisUtil.getJedis();
            jedis.set(enterprise.getAccesstoken().getBytes(), ObjectAndByte.toByteArray(enterprise));
            //刷新token，会话30天失效。相当于网站的7天内自动登录
            jedis.expire(enterprise.getAccesstoken().getBytes(), 60 * 60 * 24 * 7);
        } catch (Exception e) {
            responseData.jsonFill(2, "登录失败，服务器错误。", null);
            return responseData;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

        LoginVo loginVo = new LoginVo();
        loginVo.setId(Integer.parseInt(enterprise.getId()));
        loginVo.setAccessToken(enterprise.getAccesstoken());
        responseData.jsonFill(1, null, loginVo);
        return responseData;
    }

    @ApiOperation(value = "企业用内部密码登录", notes = "")
    @RequestMapping(value = "enterpriseLogin", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData<LoginVo> enterpriseLogin(
            @ApiParam("企业名") @RequestParam("enterpriseName") String enterpriseName,
            @ApiParam("内部密码") @RequestParam("innerPassword") String innerPassword,
            HttpServletRequest request, HttpServletResponse response) {

        ResponseData<LoginVo> responseData = new ResponseData();
        Enterprise enterprise = enterpriseService.getEnterpriseByName(enterpriseName).get(0);
        if (enterprise == null) {
            responseData.jsonFill(2, "用户不存在", null);
            return responseData;
        }
        if (!enterprise.getInnerPassword().equals(innerPassword)) {
            responseData.jsonFill(2, "用户名或密码错误。", null);
            return responseData;
        }
        enterprise.setAccesstoken(Util.getToken());

        //登录信息写入缓存
        Jedis jedis = null;
        try {
            jedis = JedisUtil.getJedis();
            jedis.set(enterprise.getAccesstoken().getBytes(), ObjectAndByte.toByteArray(enterprise));
            //刷新token，会话30天失效。相当于网站的7天内自动登录
            jedis.expire(enterprise.getAccesstoken().getBytes(), 60 * 60 * 24 * 7);
        } catch (Exception e) {
            responseData.jsonFill(2, "登录失败，服务器错误。", null);
            return responseData;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

        LoginVo loginVo = new LoginVo();
        loginVo.setId(Integer.parseInt(enterprise.getId()));
        loginVo.setAccessToken(enterprise.getAccesstoken());
        responseData.jsonFill(1, null, loginVo);
        return responseData;
    }

    @ApiOperation(value = "通过ID获取企业", notes = "")
    @RequestMapping(value = "getEnterpriseById", method = {RequestMethod.GET})
    @ResponseBody
    public ResponseData<Enterprise> getEnterpriseById(@ApiParam("") @RequestParam("id") String id) {
        ResponseData<Enterprise> responseData = new ResponseData<>();
        Enterprise enterprise = enterpriseService.getEnterpriseById(id);
        if (enterprise == null) {
            responseData.jsonFill(2, "无效的id", null);
            return responseData;
        }
        responseData.jsonFill(1, null, enterprise);
        return responseData;
    }


    @ApiOperation(value = "修改公用密码", notes = "")
    @RequestMapping(value = "modifyPassword", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData<Boolean> modifyPassword(
            @ApiParam("外部密码") @RequestParam(value = "password") String password,
            HttpServletRequest request) {

        Enterprise enterpriseInRedis = (Enterprise) request.getAttribute(TokenConfig.DEFAULT_USERID_REQUEST_ATTRIBUTE_NAME);
        ResponseData<Boolean> responseData = new ResponseData<>();
        Enterprise enterprise = new Enterprise();
        enterprise.setId(enterpriseInRedis.getId());
        enterprise.setPassword(password);
        int res = enterpriseService.updateEnterprise(enterprise);
        if (res == 0) {
            responseData.jsonFill(2, "更新失败", false);
            return responseData;
        }
        responseData.jsonFill(1, null, true);
        return responseData;
    }

    @ApiOperation(value = "修改企业内部密码", notes = "")
    @RequestMapping(value = "modifyInnerPassword", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData<Boolean> modifyInnerPassword(
            @ApiParam("外部密码") @RequestParam(value = "innerPassword") String innerPassword,
            HttpServletRequest request) {

        Enterprise enterpriseInRedis = (Enterprise) request.getAttribute(TokenConfig.DEFAULT_USERID_REQUEST_ATTRIBUTE_NAME);
        ResponseData<Boolean> responseData = new ResponseData<>();
        Enterprise enterprise = new Enterprise();
        enterprise.setId(enterpriseInRedis.getId());
        enterprise.setInnerPassword(innerPassword);
        int res = enterpriseService.updateEnterprise(enterprise);
        if (res == 0) {
            responseData.jsonFill(2, "更新失败", false);
            return responseData;
        }
        responseData.jsonFill(1, null, true);
        return responseData;
    }

    @ApiOperation(value = "获取企业信息", notes = "")
    @RequestMapping(value = "getEnterprise", method = {RequestMethod.GET})
    @ResponseBody
    public ResponseData<EnterpriseVo> getEnterpriseById(HttpServletRequest request) {
        Enterprise enterpriseInRedis = (Enterprise) request.getAttribute(TokenConfig.DEFAULT_USERID_REQUEST_ATTRIBUTE_NAME);
        ResponseData<EnterpriseVo> responseData = new ResponseData<>();
        Enterprise enterprise = enterpriseService.getEnterpriseById(enterpriseInRedis.getId());
        if (enterprise == null) {
            responseData.jsonFill(2, "不存在该企业，可能已经从系统中删除。", null);
            return responseData;
        }

        EnterpriseVo enterpriseVo = new EnterpriseVo();
        enterpriseVo.setId(enterprise.getId());
        enterpriseVo.setEnterpriseName(enterprise.getEnterpriseName());

        responseData.jsonFill(1, null, enterpriseVo);
        return responseData;
    }

}
